﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenComposite.EII.Repository;
using System.Xml;
using System.Diagnostics;
using System.Drawing.Design;
using OpenComposite.Base.Designer;

namespace OpenComposite.EII.Forms
{
	internal partial class ItemDebugViewer : Form
	{
		public ItemDebugViewer()
		{
			InitializeComponent();
		}

		public ItemDebugViewer(object item)
			: this()
		{
			_item = item;
			if ( _item != null ) {
				load();
			}
		}

		protected override void OnShown(EventArgs e)
		{
#if !DEBUG
			Close();
			return;
#else
			base.OnShown(e);
#endif
		}
		private object _item = null;

		public RepositoryItemBase RepositoryItem
		{
			get { return _item as RepositoryItemBase; }
			set
			{
				_item = value;
				if ( _item != null ) load();
			}
		}

		public DesignerControl DesignerControl
		{
			get { return _item as DesignerControl; }
			set
			{
				_item = value;
				if ( _item != null ) load();
			}
		}

		private void load()
		{
			if ( _item == null ) return;
			this.Text = string.Format("[Debug] Type: {0}", _item.GetType().FullName);
			propertyGrid1.Site = new Designer.DesignerSite(Global.Data.RepositoryService, null, null);
			propertyGrid1.SelectedObject = _item;
		}
	}


	class CodeEditorUI : UITypeEditor
	{
		public CodeEditorUI()
			: base()
		{

		}

		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			if ( value is string ) {
				string s = value.ToString();
				if ( s.StartsWith("<") ) {
					XmlDocument xd = new XmlDocument();
					xd.InnerXml = s;
					formXmlViewer xmlViewer = new formXmlViewer();
					xmlViewer.XmlDocument = xd;
					xmlViewer.ShowDialog();
				} else if ( s.StartsWith("//---") ) {
					FormCodeViewer codeForm = new FormCodeViewer();
					codeForm.Code = s;
					codeForm.ShowLineNumbers = true;
					codeForm.ShowErrors = true;
					codeForm.ShowDialog();
				} else {
					FormCodeViewer codeForm = new FormCodeViewer();
					codeForm.Code = s;
					codeForm.ShowLineNumbers = false;
					codeForm.ShowErrors = false;
					codeForm.ShowDialog();
				}
			} else if ( value is XmlDocument ) {
				formXmlViewer xmlViewer = new formXmlViewer();
				xmlViewer.XmlDocument = (XmlDocument)value;
				xmlViewer.ShowDialog();
			}
			return value;
			//return base.EditValue(context, provider, value);
		}

		public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
		{
			return UITypeEditorEditStyle.Modal;
			//return base.GetEditStyle(context);
		}
	}
}
